package com.service;
import static com.def.GenericDef.ACTION_FLG_ADD;
import static com.def.GenericDef.ACTION_FLG_CANCEL;
import static com.def.GenericDef.ACTION_FLG_DELETE;
import static com.def.GenericDef.ACTION_FLG_FILTER_DISTINCT;
import static com.def.GenericDef.ACTION_FLG_LIST_WHOLE;
import static com.def.GenericDef.ACTION_FLG_NEW;
import static com.def.GenericDef.ACTION_FLG_QUERY;
import static com.def.GenericDef.ACTION_FLG_UPDATE;
import static com.def.GenericDef.E_XPLAYOUT_NOT_BIND_SO;
import static com.def.GenericDef.ACTION_FLG_QUERY_BY_WO_ID;
import static com.def.GenericDef.E_XPLAYOUT_ADD_LAYOUT_ALREADY_EXIST;
import static com.def.GenericDef.E_XPLAYOUT_DQR_MDL_ID;
import static com.def.GenericDef.E_XPLAYOUT_NOT_FOUND_LAYOUT_;
import static com.def.GenericDef.E_XPLAYOUT_NOT_FOUND_MDL_ID;
import static com.def.GenericDef.E_XPLAYOUT_NOT_FOUND_WO;
import static com.def.GenericDef.RETURN_CODE_OK;
import static com.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.def.GenericDef.RETURN_MESG_OK;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.dao.IBisLayotDao;
import com.dao.IBisLayotGLDao;
import com.dao.IBisLayotLCDao;
import com.dao.IBisMdlDefDao;
import com.dao.IRetWODao;
import com.icim.service.ICIMBaseService;
import com.model.Bis_layot;
import com.model.Bis_layot_gl;
import com.model.Bis_layot_glId;
import com.model.Bis_layot_lc;
import com.model.Bis_mdl_def;
import com.model.Ret_wo;
import com.tx.Xplayout.XplayoutI;
import com.tx.Xplayout.XplayoutIA;
import com.tx.Xplayout.XplayoutIB;
import com.tx.Xplayout.XplayoutO;
import com.tx.Xplayout.XplayoutOA;
import com.tx.Xplayout.XplayoutOB;
import com.tx.Xplayout.XplayoutOC;
import com.util.MqOpe;

@Scope("prototype")
@Service("XplayoutService")
public class XplayoutService extends ICIMBaseService{
	private XplayoutI xplayoutI;
	private XplayoutO xplayoutO; 
	
	@Autowired
	private IBisLayotDao bisLayotDao;
	@Autowired
	private IBisLayotLCDao bisLayotLCDao;
	@Autowired
	private IBisLayotGLDao bisLayotGLDao;
	@Autowired
	private IRetWODao retWODao;
	@Autowired
	private IBisMdlDefDao bisMdlDefDao;
	@Autowired
	private MqOpe mqOpe;
	
	private Logger logger = Logger.getLogger(XplayoutService.class);
	
	public String subMainProc(String strInMsg){
		logger.info("InTrx is "+ strInMsg );
		try{
			Session session = bisLayotDao.getCrSession();
			xplayoutI = new XplayoutI();
			xplayoutO = new XplayoutO();
			xplayoutI = (XplayoutI) mqOpe.inStr2Obj(strInMsg,xplayoutI);
			xplayoutO.setTrx_id("XPLAYOUT");
			xplayoutO.setType_id("O");
			xplayoutO.setRtn_code(RETURN_CODE_OK);
			xplayoutO.setRtn_mesg(RETURN_MESG_OK);
			char action_flg = xplayoutI.getAction_flg().charAt(0);
			switch( action_flg ){
				case ACTION_FLG_QUERY           :  queryByCondition()       ; break;   
				case ACTION_FLG_ADD             :  addORUpdateLocationFnc() ; break;
				case ACTION_FLG_UPDATE          :  updateFnc()              ; break;
				case ACTION_FLG_DELETE          :  deleteFnc()              ; break;
				case ACTION_FLG_FILTER_DISTINCT :  listDistinctFnc()        ; break;
				case ACTION_FLG_NEW             :  addORUpdateGroupFnc()    ; break;
				case ACTION_FLG_CANCEL          :  deleteByConditionFnc()   ; break;
				case ACTION_FLG_LIST_WHOLE      :  listWholeFnc()           ; break;
				case ACTION_FLG_QUERY_BY_WO_ID  :  queryByWOIDFnc()         ; break;
				default                         :  errActionFnc();   
			}
			if(RETURN_CODE_OK.equals( xplayoutO.getRtn_code() )){
				session.flush();
			}else{
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
			
		}
		catch(Exception ex){
			xplayoutO.setRtn_code(RETURN_CODE_UNKNOWN);
			xplayoutO.setRtn_mesg(ex.toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}finally{
			logger.info(mqOpe.obj2Str(xplayoutO));
		}
		return mqOpe.obj2Str(xplayoutO);
	}
	public void addFnc(){
		XplayoutIA iary = xplayoutI.getIary().get(0);
		String layot_id = iary.getLayot_id();
		Bis_layot bis_layot = bisLayotDao.get(layot_id);
		if( bis_layot != null ){
			xplayoutO.setRtn_code(E_XPLAYOUT_ADD_LAYOUT_ALREADY_EXIST+"");
			xplayoutO.setRtn_mesg("bis_layot Already exist,Please Check");
			return ;
		}
		bis_layot = new Bis_layot();
		bis_layot.setLayot_id(iary.getLayot_id());
		bis_layot.setLayot_dsc(iary.getLayot_dsc());
		bis_layot.setLayot_flg(iary.getLayot_flg());
		bis_layot.setLayot_cate(iary.getLayot_cate());
		bis_layot.setX_axis_cnt(iary.getX_axis_cnt());
		bis_layot.setX_axis_len(iary.getX_axis_len());
		bis_layot.setY_axis_cnt(iary.getY_axis_cnt());
		bis_layot.setY_axis_len(iary.getY_axis_len());
		bisLayotDao.save(bis_layot);
	}
	public void updateFnc(){
		XplayoutIA iary = xplayoutI.getIary().get(0);
		String layot_id = iary.getLayot_id();
		Bis_layot bis_layot = bisLayotDao.get(layot_id);
		if( bis_layot == null ){
			xplayoutO.setRtn_code(E_XPLAYOUT_NOT_FOUND_LAYOUT_+"");
			xplayoutO.setRtn_mesg("bis_layot not found Record,Please Check");
			return ;
		}
		bis_layot.setLayot_id(iary.getLayot_id());
		bis_layot.setLayot_dsc(iary.getLayot_dsc());
		bis_layot.setLayot_cate(iary.getLayot_cate());
		bis_layot.setX_axis_cnt(iary.getX_axis_cnt());
		bis_layot.setX_axis_len(iary.getX_axis_len());
		bis_layot.setY_axis_cnt(iary.getY_axis_cnt());
		bis_layot.setY_axis_len(iary.getY_axis_len());
		bisLayotDao.update(bis_layot);
	}
	public void deleteFnc(){
		XplayoutIA iary   = xplayoutI.getIary().get(0);
		String layot_id   = iary.getLayot_id();
		Bis_layot bis_layot = bisLayotDao.get(layot_id);
		if(bis_layot==null){
			xplayoutO.setRtn_code(E_XPLAYOUT_NOT_FOUND_LAYOUT_+"");
			xplayoutO.setRtn_mesg("bis_layot not found Record,Please Check");
			return ;
			
		}
		if(bis_layot.getLayot_cate()=="G"){
			String hql = "FROM Bis_layot_gl where id.layotg_id_fk='"+ layot_id +"'";
			List<Bis_layot_gl>bisLayotGList = bisLayotGLDao.find(hql);
			if(bisLayotGList.size()>0){
				for(Bis_layot_gl bis_layot_gl:bisLayotGList){
					bisLayotGLDao.delete(bis_layot_gl);
				}
			}
		}
		bisLayotDao.delete(bis_layot);
	}
	public void queryByCondition(){
		XplayoutIA  iary = xplayoutI.getIary().get(0);
		String hql = " FROM Bis_layot where 1=1 ";
		String layot_id;
		String layot_flg;
		Ret_wo ret_wo = new Ret_wo();
		if(iary.getWo_id()!=null){
			 ret_wo = retWODao.get(iary.getWo_id());
		}
		if(("007".equals(ret_wo.getCus_id_fk()))|| ("006".equals(ret_wo.getCus_id_fk()))){
			layot_id   = iary.getLayot_id();
			layot_flg  = iary.getLayot_flg();
		}else {
			layot_id=ret_wo.getLayoutId();
			layot_flg=null;
		}
		if( layot_id != null ){
			hql = hql + " and id.layot_id = '" + layot_id +  "'";
		}
		if(layot_flg!=null){
			hql = hql +" and layot_flg ='"+layot_flg +"'";
		}
		List<XplayoutOA> oaryList = new ArrayList<XplayoutOA>();
		List<Bis_layot> layotList = bisLayotDao.find(hql);
		for(Bis_layot bis_layot: layotList){
			XplayoutOA oary = new XplayoutOA();
			oary.setLayot_id(bis_layot.getLayot_id());
			oary.setLayot_flg(bis_layot.getLayot_flg());
			oary.setLayot_dsc(bis_layot.getLayot_dsc());
			oary.setLayot_cate(bis_layot.getLayot_cate());
			oary.setX_axis_cnt(bis_layot.getX_axis_cnt());
			oary.setX_axis_len(bis_layot.getX_axis_len());
			oary.setY_axis_cnt(bis_layot.getY_axis_cnt());
			oary.setY_axis_len(bis_layot.getY_axis_len());
			oary.setLot_std_qty(bis_layot.getLot_std_qty());
			oary.setPos_len(bis_layot.getPos_len());
			oary.setSub_id(bis_layot.getSub_id());
			if(("G").equals(bis_layot.getLayot_flg()) &&layotList.size()==1){
				String hql2 = "FROM Bis_layot_gl where id.layotg_id_fk='"+ bis_layot.getLayot_id()+"'";
				List<Bis_layot_gl> bisLayotGLList = bisLayotGLDao.find(hql2);
				List<XplayoutOB> oaryBList = new ArrayList<XplayoutOB>();
				for(Bis_layot_gl bis_layot_gl:bisLayotGLList){
					XplayoutOB oaryB = new XplayoutOB();
					Bis_layot bis_layot_2 = bisLayotDao.get(bis_layot_gl.getId().getLayot_id_fk());
					oaryB.setLayotg_id_fk(bis_layot_gl.getId().getLayotg_id_fk());
					oaryB.setLayot_id_fk(bis_layot_gl.getId().getLayot_id_fk());
					oaryB.setX_axis(bis_layot_gl.getId().getX_axis());
					oaryB.setY_axis(bis_layot_gl.getId().getY_axis());
					oaryB.setMrr_loc(bis_layot_gl.getMrr_loc());
					oaryB.setPos_id(bis_layot_gl.getPos_id());
					oaryB.setLayot_dsc(bis_layot_2.getLayot_dsc());
					oaryBList.add(oaryB);
				}
				if(bisLayotGLList.size()>0){
					oary.setOaryB(oaryBList);
					oary.setTbl_cnt_b(oaryBList.size());
				}
			}else if(layotList.size()==1){
				String hql3 = "FROM Bis_layot_lc where id.layot_id_fk='"+bis_layot.getLayot_id()+"'";
				List<Bis_layot_lc> bisLayotLCList = bisLayotLCDao.find(hql3);
				List<XplayoutOC> oaryCList  = new ArrayList<XplayoutOC>();
				for(Bis_layot_lc bis_layot_lc:bisLayotLCList){
					XplayoutOC oaryC = new XplayoutOC();
					oaryC.setLayot_id_fk(bis_layot_lc.getId().getLayot_id_fk());
					oaryC.setX_axis(bis_layot_lc.getId().getX_axis());
					oaryC.setY_axis(bis_layot_lc.getId().getY_axis());
					oaryC.setPos_id(bis_layot_lc.getPos_id());
					oaryC.setMrr_loc(bis_layot_lc.getMrr_loc());
					oaryC.setPos_dsc(bis_layot_lc.getPos_dsc());
					oaryCList.add(oaryC);
				}
				if(bisLayotLCList.size()>0){
					oary.setOaryC(oaryCList);
					oary.setTbl_cnt_c(oaryCList.size());
				}
			}
			oaryList.add(oary);
		}
		xplayoutO.setOary(oaryList);
		xplayoutO.setTbl_cnt(oaryList.size());
		
	}
	public void listDistinctFnc(){
	} 
	public void deleteByConditionFnc(){
	}
	
	public void listWholeFnc(){
		List<XplayoutOA> oaryList = new ArrayList<XplayoutOA>();
		
		String hql = "FROM Bis_layot";
		List<Bis_layot> bisLayotList = bisLayotDao.find(hql);
		for(Bis_layot bis_layot :bisLayotList){
			XplayoutOA oary = new XplayoutOA();
			oary.setLayot_id(bis_layot.getLayot_id());
			oary.setLayot_dsc(bis_layot.getLayot_dsc());
			oary.setX_axis_cnt(bis_layot.getX_axis_cnt());
			oary.setY_axis_cnt(bis_layot.getY_axis_cnt());
			oaryList.add(oary);
		}
		xplayoutO.setOary(oaryList);
		xplayoutO.setTbl_cnt(oaryList.size());
	}
	public void addORUpdateLocationFnc(){
		XplayoutIA iary = xplayoutI.getIary().get(0);
		//如果bis_layot ,则新增一笔
		String layot_id = iary.getLayot_id();
		Bis_layot bis_layot = bisLayotDao.get(layot_id);
		if( bis_layot == null ){
			addFnc();
		}else{
			updateFnc();
		}
	}
	public void addORUpdateGroupFnc(){
		XplayoutIA iary = xplayoutI.getIary().get(0);
		List<XplayoutIB> iaryBList = iary.getIaryB();
		//如果Bis_layot表中没有记录 则新增一笔
		String layot_id = iary.getLayot_id();
		Bis_layot bis_layot = bisLayotDao.get(layot_id);
		if( bis_layot == null ){
			addFnc();
		}else{
			updateFnc();
		}
		//删除Bis_layot_gl下 layout_group所有记录
		String hql = "FROM Bis_layot_gl where id.layotg_id_fk='"+ layot_id +"'";
		List<Bis_layot_gl> bisLayotGLList = bisLayotGLDao.find(hql);
		for(Bis_layot_gl bis_layot_gl:bisLayotGLList){
			bisLayotGLDao.delete(bis_layot_gl);
		}
		for(XplayoutIB iaryB: iaryBList ){
			Bis_layot_gl  bis_layot_gl = new Bis_layot_gl();
			Bis_layot_glId id = new Bis_layot_glId();
			id.setLayotg_id_fk(iaryB.getLayotg_id_fk());
			id.setLayot_id_fk(iaryB.getLayot_id_fk());//TODO:是否需要查询Bis_layot表确认是否存在  //不需要
			id.setX_axis(iaryB.getX_axis());
			id.setY_axis(iaryB.getY_axis());
			bis_layot_gl.setId(id);
			bis_layot_gl.setMrr_loc(iaryB.getMrr_loc());
			bis_layot_gl.setPos_id(iaryB.getPos_id());
			bisLayotGLDao.save(bis_layot_gl);
		}
	}
	public void queryByWOIDFnc(){
	   XplayoutIA iary = xplayoutI.getIary().get(0);
	   Ret_wo ret_wo = retWODao.get(iary.getWo_id());
		if( ret_wo == null){
			xplayoutO.setRtn_code(E_XPLAYOUT_NOT_FOUND_WO+"");
			xplayoutO.setRtn_mesg("Not found Record[wo_id:"+iary.getWo_id()+"] in RET_WO");
			return ;
		}
		if("Y".equals(xplayoutI.getBind_so_flg())){
			if(ret_wo.getMdl_id_fk() == null){
				xplayoutO.setRtn_code(E_XPLAYOUT_NOT_BIND_SO + "");
				xplayoutO.setRtn_mesg("此内部订单［"+iary.getWo_id()+"］ 没有绑定商务订单，请去5200完成绑定！");
				return ;
			}
			
		}
	   Bis_mdl_def bis_mdl_def =  bisMdlDefDao.get(ret_wo.getMdl_id_fk());
	   if( bis_mdl_def == null ){
		   xplayoutO.setRtn_code(E_XPLAYOUT_NOT_FOUND_MDL_ID+ "");
		   xplayoutO.setRtn_mesg("Not found Record[mdl_id_fk:"+ret_wo.getMdl_id_fk()+"] in BIS_MDL_DEF");
		   return ;
	   }
	   
	   String dqr_flg = (bis_mdl_def.getRsv_info() != null && bis_mdl_def.getRsv_info().charAt(1) == 'Y') ? "Y" : "N";
	   if(dqr_flg == "Y"){
		   xplayoutO.setRtn_code(E_XPLAYOUT_DQR_MDL_ID + "");
		   xplayoutO.setRtn_mesg("内部订单：["+iary.getWo_id()
				   +"]的产品型号["+ret_wo.getMdl_id_fk()
				   +"]版式为["+ bis_mdl_def.getLayot_id_fk() 
				   +"]，请确定是否正确，如不正确请修正!");
		   return ;
	   }
	   if("006".equals(ret_wo.getCus_id_fk())||"007".equals(ret_wo.getCus_id_fk())){
		   xplayoutI.getIary().get(0).setLayot_id(bis_mdl_def.getLayot_id_fk());
	   }else {
		   xplayoutI.getIary().get(0).setLayot_id(ret_wo.getLayoutId());
	   }
	   queryByCondition();

	}
	public void errActionFnc(){
		xplayoutO.setTrx_id("XPLAYOUT");
		xplayoutO.setType_id("O");
		xplayoutO.setRtn_code("0000009");
		xplayoutO.setRtn_mesg("Invalid Action_flg");
	}
	
}
